﻿using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace bonus.Controllers
{
	public class MemberController : Controller
	{
		/// <summary>
		/// 用户中心
		/// </summary>
		/// <returns></returns>
		public ActionResult Index()
		{
			if (TempData["Pwd2"] != null && TempData["Pwd2"].ToString() == "True")
			{
				Repository.Repository tool = new Repository.Repository();

				var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

				return View(user);
			}
			else
			{
				return RedirectToAction("SecondaryPwd", new { url = "/Member/Index" });
			}

		}
		/// <summary>
		/// 用户关系
		/// </summary>
		/// <returns></returns>
		public ActionResult MerberList()
		{
			return View();
		}

		/// <summary>
		/// 用户列表
		/// </summary>
		/// <returns></returns>
		public ActionResult MerberLists()
		{
			return View();
		}
		/// <summary>
		/// 用户修改
		/// </summary>
		/// <returns></returns>
		public ActionResult MerberAmend()
		{
			if (TempData["Pwd2"] != null && TempData["Pwd2"].ToString() == "True")
			{
				Repository.Repository tool = new Repository.Repository();

				var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

				return View(user);
			}
			else
			{
				return RedirectToAction("SecondaryPwd", new { url = "/Member/MerberAmend" });
			}
		}

		/// <summary>
		/// 二级密码页面
		/// </summary>
		/// <returns></returns>
		public ActionResult SecondaryPwd()
		{
			return View();
		}

		/// <summary>
		/// 密码修改
		/// </summary>
		/// <returns></returns>
		public ActionResult ChangePaw()
		{
			return View();
		}

		/// <summary>
		/// 密码找回页面
		/// </summary>
		/// <returns></returns>
		public ActionResult RetrievePaw()
		{
			return View();
		}
		/// <summary>
		/// 验证二级密码
		/// </summary>
		/// <param name="pwd"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult VerifyPwd(string pwd)
		{
			Repository.Repository tool = new Repository.Repository();
			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

			if (user == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户存在" });
			}

			if (!Repository.FuBeiMD5.Verify(pwd, user.Pwd2, Models.WebConfig.KEY, Models.WebConfig.UFT8))
			{
				return Json(new { Code = "FAIL", Msg = "密码错误" });
			}

			TempData["Pwd2"] = true;

			return Json(new { Code = "OK", Msg = "验证成功" });
		}


		/// <summary>
		/// 修改密码
		/// </summary>
		/// <param name="pwd"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult EditPwd(string oldPwd, string pwd, int type)
		{
			Repository.Repository tool = new Repository.Repository();
			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (user == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			if (type == 0)
			{
				if (!Repository.FuBeiMD5.Verify(oldPwd, user.Pwd1, Models.WebConfig.KEY, Models.WebConfig.UFT8))
				{
					return Json(new { Code = "FAIL", Msg = "老密码错误" });
				}
				var update = Builders<Models.User>.Update.Set("Pwd1", Repository.FuBeiMD5.Sign(pwd, Models.WebConfig.KEY, Models.WebConfig.UFT8));

				var result = tool.UpdateOne(user._id.ToString(), update);
			}
			else
			{
				if (!Repository.FuBeiMD5.Verify(oldPwd, user.Pwd2, Models.WebConfig.KEY, Models.WebConfig.UFT8))
				{
					return Json(new { Code = "FAIL", Msg = "老密码错误" });
				}
				var update = Builders<Models.User>.Update.Set("Pwd2", Repository.FuBeiMD5.Sign(pwd, Models.WebConfig.KEY, Models.WebConfig.UFT8));

				var result = tool.UpdateOne(user._id.ToString(), update);
			}

			return Json(new { Code = "OK", Msg = "修改成功" });
		}

		/// <summary>
		/// 修改个人信息
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public JsonResult EditInfo(string name, string card, string bname, string cards)
		{
			Repository.Repository tool = new Repository.Repository();
			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (user == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户存在" });
			}
			user.Name = name;
			user.BankNO = card;
			user.BankName = bname;
			if (!string.IsNullOrEmpty(cards) && string.IsNullOrEmpty(user.Card))
			{
				user.Card = cards;
			}

			var update = Builders<Models.User>.Update.Set("Name", name).Set("BankNO", card).Set("BankName", bname).Set("Card", user.Card);

			var result = tool.UpdateOne(user._id.ToString(), update);

			return Json(new { Code = "OK", Msg = "修改成功" });

		}


		/// <summary>
		/// 忘记密码
		/// </summary>
		/// <param name="no">用户编号</param>
		/// <param name="name">用户名称</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult RetrievePwd(string no, string name)
		{

			Repository.Repository tool = new Repository.Repository();

			var filter = Builders<Models.User>.Filter.Eq("NO", no);

			var entity = tool.GetOne(filter);

			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "编号不存在" });
			}
			if (string.IsNullOrEmpty(name) && entity.Name != name)
			{
				return Json(new { Code = "FAIL", Msg = "用户名错误" });
			}

			string pwd1 = GetRandomString(6);

			string pwd = Repository.FuBeiMD5.Sign(pwd1, Models.WebConfig.KEY, Models.WebConfig.UFT8);

			var updata = Builders<Models.User>.Update.Set("Pwd1", pwd).Set("Pwd2", pwd);

			var result = tool.UpdateOne(entity._id.ToString(), updata);

			return Json(new { Code = "OK", Msg = "修改成功", Pwd = pwd1 });
		}

		///<summary>
		///生成随机字符串 
		///</summary>
		///<param name="length">目标字符串的长度</param>
		///<param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
		///<returns>指定长度的随机字符串</returns>
		public static string GetRandomString(int length)
		{
			byte[] b = new byte[4];
			new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
			Random r = new Random(BitConverter.ToInt32(b, 0));
			string s = null, str = "";
			str += "0123456789";
			str += "abcdefghijklmnopqrstuvwxyz";
			str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			//str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
			for (int i = 0; i < length; i++)
			{
				s += str.Substring(r.Next(0, str.Length - 1), 1);
			}
			return s;
		}


		/// <summary>
		/// 提交提现申请
		/// </summary>
		/// <param name="money">提现金额</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Withdraw(int money)
		{

			if (money < 50)
			{
				return Json(new { Code = "FAIL", Msg = "每次提现金额需大于50元" });
			}

			Repository.Repository tool = new Repository.Repository();

			var entity = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			if (string.IsNullOrEmpty(entity.Card))
			{
				return Json(new { Code = "FAIL", Msg = "请先完善身份证号码" });
			}

			if (entity.Money < money)
			{
				return Json(new { Code = "FAIL", Msg = "余额不足" });
			}

			Models.Journal journal = new Models.Journal();

			journal.AddDT = DateTime.Now;
			journal.In = 0;
			journal.GetNO = entity.NO;
			journal.Name = entity.Name;
			journal.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
			journal.Operator = "Sys";
			journal.Out = money;
			journal.Remarks = "提现:" + money + ";";
			journal.OrderMoney = 0;
			journal.OrderNo = "";
			journal.State = 0;
			journal.Rest = entity.Money - money;
			journal.Type = Models.Journal.TypeClass.WITHDRAW;
			journal.Title = Models.Journal.TypeClass.GetType(journal.Type) + ";";
			journal._id = ObjectId.GenerateNewId();

			var result = tool.AddOneAsync(journal);

			var updata = Builders<Models.User>.Update.Set("Money", entity.Money - money).Set("Freeze", entity.Freeze + money);

			var upresult = tool.UpdateOne(entity._id.ToString(), updata);

			return Json(new { Code = "OK", Msg = "已提交" });
		}


		/// <summary>
		/// 修改用户注册时间
		/// </summary>
		/// <param name="userId">用户标识</param>
		/// <param name="dt">入驻时间</param>
		/// <returns></returns>
		public JsonResult EditAddDT(string userId, DateTime dt)
		{
			Repository.Repository tool = new Repository.Repository();
			var entity = tool.GetOne<Models.User>(userId);
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			var updatau = Builders<Models.User>.Update.Set("AddDT", dt);

			var resultu = tool.UpdateOne(userId, updatau);

			return Json(new { Code = "OK", Msg = "修改成功", Title = dt.ToString("yyyy-MM-dd") });
		}

		/// <summary>
		/// 给用户和用户上级加经验点
		/// </summary>
		/// <param name="userId">用户标识</param>
		/// <param name="dt">入驻时间</param>
		/// <returns></returns>
		public JsonResult AddEXs(string userId, int EX)
		{
			Repository.Repository tool = new Repository.Repository();
			var sales = tool.GetOne<Models.User>(userId);
			if (sales == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			string grade = "";

			string exp = sales.EXP;



			while (sales != null)
			{
				if (sales.UserType == Models.User.TypeClass.User)
				{
					if (sales.Level < Models.User.LevelClass.LAOSHI && (Convert.ToInt32(sales.EXP) + EX) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString()).Set("Level", sales.Level + 1);

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
						grade = Models.User.LevelClass.GetLevel(sales.Level + 1);
					}
					else if (sales.Level == Models.User.LevelClass.LAOSHI && (Convert.ToInt32(sales.EXP) + EX) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
					{
						var fil = Builders<Models.User>.Filter.Where(p => p.EUP == sales.NO && p.Level >= Models.User.LevelClass.LAOSHI);
						var count = tool.Count(fil);
						if (count >= 2)
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString()).Set("Level", sales.Level + 1);

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
							grade = Models.User.LevelClass.GetLevel(sales.Level + 1);
						}
						else
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString());

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
							grade = Models.User.LevelClass.GetLevel(sales.Level);
						}
					}
					else if (sales.Level == Models.User.LevelClass.DAOSHI && (Convert.ToInt32(sales.EXP) + EX) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
					{
						var fil = Builders<Models.User>.Filter.Where(p => p.EUP == sales.NO && p.Level == Models.User.LevelClass.DAOSHI);
						var count = tool.Count(fil);
						if (count >= 4 || ((Convert.ToInt32(sales.EXP) + EX) > 18000000 && count >= 3) || ((Convert.ToInt32(sales.EXP) + EX) > 24000000 && count >= 2))
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString()).Set("Level", sales.Level + 1);

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
							grade = Models.User.LevelClass.GetLevel(sales.Level + 1);
						}
						else
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString());

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
							grade = Models.User.LevelClass.GetLevel(sales.Level);
						}
					}
					else
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString());

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
						grade = Models.User.LevelClass.GetLevel(sales.Level);
					}

				}

				if (string.IsNullOrEmpty(sales.EUP))
				{
					sales = null;
				}
				else
				{
					var fil = Builders<Models.User>.Filter.Where(p => p.NO == sales.EUP);
					sales = tool.GetOne(fil);
				}
			}

			return Json(new { Code = "OK", Msg = "追加成功", Grade = grade, Title = (Convert.ToInt32(exp) + EX).ToString() });
		}

		/// <summary>
		/// 给用户加经验点
		/// </summary>
		/// <param name="userId">用户标识</param>
		/// <param name="dt">入驻时间</param>
		/// <returns></returns>
		public JsonResult AddEX(string userId, int EX)
		{
			Repository.Repository tool = new Repository.Repository();
			var sales = tool.GetOne<Models.User>(userId);
			if (sales == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			string grade = "";

			if (sales.UserType == Models.User.TypeClass.User)
			{
				if (sales.Level < Models.User.LevelClass.LAOSHI && (Convert.ToInt32(sales.EXP) + EX) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
				{
					var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString()).Set("Level", sales.Level + 1);

					var addresult = tool.UpdateOne(sales._id.ToString(), update);
					grade = Models.User.LevelClass.GetLevel(sales.Level + 1);
				}
				else if (sales.Level == Models.User.LevelClass.LAOSHI && (Convert.ToInt32(sales.EXP) + EX) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
				{
					var fil = Builders<Models.User>.Filter.Where(p => p.EUP == sales.NO && p.Level >= Models.User.LevelClass.LAOSHI);
					var count = tool.Count(fil);
					if (count >= 2)
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString()).Set("Level", sales.Level + 1);

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
						grade = Models.User.LevelClass.GetLevel(sales.Level + 1);
					}
					else
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString());

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
						grade = Models.User.LevelClass.GetLevel(sales.Level);
					}
				}
				else if (sales.Level == Models.User.LevelClass.DAOSHI && (Convert.ToInt32(sales.EXP) + EX) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
				{
					var fil = Builders<Models.User>.Filter.Where(p => p.EUP == sales.NO && p.Level == Models.User.LevelClass.DAOSHI);
					var count = tool.Count(fil);
					if (count >= 4 || ((Convert.ToInt32(sales.EXP) + EX) > 18000000 && count >= 3) || ((Convert.ToInt32(sales.EXP) + EX) > 24000000 && count >= 2))
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString()).Set("Level", sales.Level + 1);

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
						grade = Models.User.LevelClass.GetLevel(sales.Level + 1);
					}
					else
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString());

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
						grade = Models.User.LevelClass.GetLevel(sales.Level);
					}
				}
				else
				{
					var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + EX).ToString());

					var addresult = tool.UpdateOne(sales._id.ToString(), update);
					grade = Models.User.LevelClass.GetLevel(sales.Level);
				}

			}

			return Json(new { Code = "OK", Msg = "追加成功", Grade = grade, Title = (Convert.ToInt32(sales.EXP) + EX).ToString() });
		}

		/// <summary>
		/// 暂停金钱返现
		/// </summary>
		/// <param name="userId">用户标识</param>
		/// <returns></returns>
		public JsonResult StopMoney(string userId)
		{
			Repository.Repository tool = new Repository.Repository();
			var entity = tool.GetOne<Models.User>(userId);
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			var updatau = Builders<Models.User>.Update.Set("IsMStop", !entity.IsMStop);

			var resultu = tool.UpdateOne(userId, updatau);

			return Json(new { Code = "OK", Msg = "已" + (entity.IsMStop ? "开通" : "暂停"), Title = !entity.IsMStop ? "开通" : "暂停" });
		}

		/// <summary>
		/// 暂停经验返现
		/// </summary>
		/// <param name="userId">用户标识</param>
		/// <returns></returns>
		public JsonResult StopEXP(string userId)
		{
			Repository.Repository tool = new Repository.Repository();
			var entity = tool.GetOne<Models.User>(userId);
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}



			var updatau = Builders<Models.User>.Update.Set("IsEStop", !entity.IsEStop);

			var resultu = tool.UpdateOne(userId, updatau);

			return Json(new { Code = "OK", Msg = "已" + (entity.IsEStop ? "开通" : "暂停"), Title = !entity.IsEStop ? "开通" : "暂停" });
		}


		/// <summary>
		/// 获取子节点数据金钱上级
		/// </summary>
		/// <param name="id">上级标识</param>
		/// <returns></returns>
		[HttpPost]
		public string LoadTreeMUP(long id = 0)
		{
			List<TreeModel> list = new List<TreeModel>();
			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (user == null)
			{
				var jsonSerializerSettings1 = new JsonSerializerSettings
				{
					ContractResolver = new CamelCasePropertyNamesContractResolver()
				};
				return JsonConvert.SerializeObject(list, Formatting.None, jsonSerializerSettings1);
			}

			if (id == 0)
			{
				if (user.UserType == Models.User.TypeClass.ADMIN)
				{
					var filter = Builders<Models.User>.Filter.Where(p => string.IsNullOrEmpty(p.MUP) && p.UserType == Models.User.TypeClass.User);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();

						string nostr = item.NO;
						string r = Regex.Replace(nostr, @"^[A-Za-z]+", string.Empty);
						tree.Id = Convert.ToInt64(r);
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.MUP == item.NO);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}
				}
				else if (user.UserType == Models.User.TypeClass.COMPANY)
				{
					var filterss = Builders<Models.User>.Filter.Where(p => p.Cantent == user.NO && p.UserType == Models.User.TypeClass.CONTENT);
					var con = tool.GetMany(filterss);

					List<string> lists = new List<string>();

					foreach (var item in con)
					{
						lists.Add(item.NO);
					}

					var filter = Builders<Models.User>.Filter.Where(p => (p.Cantent == user.NO || lists.Contains(p.Cantent)) && p.UserType == Models.User.TypeClass.User);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();

						string nostr = item.NO;
						string r = Regex.Replace(nostr, @"^[A-Za-z]+", string.Empty);
						tree.Id = Convert.ToInt64(r);
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.MUP == item.NO);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}

				}
				else if (user.UserType == Models.User.TypeClass.CONTENT)
				{

					var filter = Builders<Models.User>.Filter.Where(p => p.Cantent == user.NO && p.UserType == Models.User.TypeClass.User);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();

						string nostr = item.NO;
						string r = Regex.Replace(nostr, @"^[A-Za-z]+", string.Empty);
						tree.Id = Convert.ToInt64(r);
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.MUP == item.NO);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}
				}


			}
			else
			{
				var str = "";
				var idstr = id.ToString();
				if (idstr.Length == 6)
				{
					str = "SY" + idstr;
				}
				else if (idstr.Length == 5)
				{
					str = "CO" + idstr;
				}
				else if (idstr.Length == 4)
				{
					str = "CM" + idstr;
				}

				var filter = Builders<Models.User>.Filter.Where(p => p.MUP == str && p.UserType == Models.User.TypeClass.User);
				var users = tool.GetMany(filter);

				foreach (var item in users)
				{
					TreeModel tree = new TreeModel();
					string nostr = item.NO;
					string r = Regex.Replace(nostr, @"^[A-Za-z]+", string.Empty);
					tree.Id = Convert.ToInt64(r);
					tree.PId = Convert.ToInt64(Regex.Replace(item.MUP, @"^[A-Za-z]+", string.Empty));
					tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
					var filters = Builders<Models.User>.Filter.Where(p => p.MUP == item.NO);
					var count = tool.Count(filters);
					if (count > 0)
					{
						tree.IsParent = true;
						tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
					}
					else
					{
						tree.IsParent = false;
						tree.icon = "/LinScript/zTree/css/img/diy/3.png";
					}
					list.Add(tree);
				}
			}
			var jsonSerializerSettings = new JsonSerializerSettings
			{
				ContractResolver = new CamelCasePropertyNamesContractResolver()
			};
			return JsonConvert.SerializeObject(list, Formatting.None, jsonSerializerSettings);
		}


		/// <summary>
		/// 获取子节点数据经验上级
		/// </summary>
		/// <param name="id">上级标识</param>
		/// <returns></returns>
		[HttpPost]
		public string LoadTreeEUP(long id = 0)
		{
			List<TreeModel> list = new List<TreeModel>();
			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (user == null)
			{
				var jsonSerializerSettings1 = new JsonSerializerSettings
				{
					ContractResolver = new CamelCasePropertyNamesContractResolver()
				};
				return JsonConvert.SerializeObject(list, Formatting.None, jsonSerializerSettings1);
			}

			if (id == 0)
			{
				if (user.UserType == Models.User.TypeClass.ADMIN)
				{
					var filter = Builders<Models.User>.Filter.Where(p => string.IsNullOrEmpty(p.EUP) && p.UserType == Models.User.TypeClass.User);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						string nostr = item.NO;
						string r = Regex.Replace(nostr, @"^[A-Za-z]+", string.Empty);
						tree.Id = Convert.ToInt64(r);
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.EUP == item.NO);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}
				}
				else if (user.UserType == Models.User.TypeClass.COMPANY)
				{
					var filterss = Builders<Models.User>.Filter.Where(p => p.Cantent == user.NO && p.UserType == Models.User.TypeClass.CONTENT);
					var con = tool.GetMany(filterss);

					List<string> lists = new List<string>();

					foreach (var item in con)
					{
						lists.Add(item.NO);
					}

					var filter = Builders<Models.User>.Filter.Where(p => (p.Cantent == user.NO || lists.Contains(p.Cantent)) && p.UserType == Models.User.TypeClass.User);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						string nostr = item.NO;
						string r = Regex.Replace(nostr, @"^[A-Za-z]+", string.Empty);
						tree.Id = Convert.ToInt64(r);
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.EUP == item.NO);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}

				}
				else if (user.UserType == Models.User.TypeClass.CONTENT)
				{
					var filter = Builders<Models.User>.Filter.Where(p => p.Cantent == user.NO && p.UserType == Models.User.TypeClass.User);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						string nostr = item.NO;
						string r = Regex.Replace(nostr, @"^[A-Za-z]+", string.Empty);
						tree.Id = Convert.ToInt64(r);
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.EUP == item.NO);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}
				}
			}
			else
			{
				var str = "";
				var idstr = id.ToString();
				if (idstr.Length == 6)
				{
					str = "SY" + idstr;
				}
				else if (idstr.Length == 5)
				{
					str = "CO" + idstr;
				}
				else if (idstr.Length == 4)
				{
					str = "CM" + idstr;
				}

				var filter = Builders<Models.User>.Filter.Where(p => p.EUP == str && p.UserType == Models.User.TypeClass.User);
				var users = tool.GetMany(filter);

				foreach (var item in users)
				{
					TreeModel tree = new TreeModel();
					tree.Id = Convert.ToInt64(Regex.Replace(item.NO, @"^[A-Za-z]+", string.Empty));
					tree.PId = Convert.ToInt64(Regex.Replace(item.EUP, @"^[A-Za-z]+", string.Empty));
					tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
					var filters = Builders<Models.User>.Filter.Where(p => p.EUP == item.NO);
					var count = tool.Count(filters);
					if (count > 0)
					{
						tree.IsParent = true;
						tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
					}
					else
					{
						tree.IsParent = false;
						tree.icon = "/LinScript/zTree/css/img/diy/3.png";
					}
					list.Add(tree);
				}
			}
			var jsonSerializerSettings = new JsonSerializerSettings
			{
				ContractResolver = new CamelCasePropertyNamesContractResolver()
			};
			return JsonConvert.SerializeObject(list, Formatting.None, jsonSerializerSettings);

		}

		/// <summary>
		/// 获取子节点数据公司
		/// </summary>
		/// <param name="id">上级标识</param>
		/// <returns></returns>
		[HttpPost]
		public string LoadTreeCompany(long id = 0)
		{
			List<TreeModel> list = new List<TreeModel>();
			Repository.Repository tool = new Repository.Repository();
			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (user == null)
			{
				var jsonSerializerSettings1 = new JsonSerializerSettings
				{
					ContractResolver = new CamelCasePropertyNamesContractResolver()
				};
				return JsonConvert.SerializeObject(list, Formatting.None, jsonSerializerSettings1);
			}

			if (id == 0)
			{
				if (user.UserType == Models.User.TypeClass.ADMIN)
				{
					var filter = Builders<Models.User>.Filter.Where(p => string.IsNullOrEmpty(p.MUP) && string.IsNullOrEmpty(p.EUP) && p.UserType == Models.User.TypeClass.COMPANY);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						tree.Id = Convert.ToInt64(Regex.Replace(item.NO, @"^[A-Za-z]+", string.Empty));
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.Cantent == item.NO && p.UserType == Models.User.TypeClass.CONTENT);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}
				}
				else if (user.UserType == Models.User.TypeClass.COMPANY)
				{
					var filter = Builders<Models.User>.Filter.Where(p => p.Cantent == user.NO && p.UserType == Models.User.TypeClass.CONTENT);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						tree.Id = Convert.ToInt64(Regex.Replace(item.NO, @"^[A-Za-z]+", string.Empty));
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.Cantent == item.NO && p.UserType == Models.User.TypeClass.CONTENT);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}
				}
				else if (user.UserType == Models.User.TypeClass.CONTENT)
				{
					var filter = Builders<Models.User>.Filter.Where(p => p.NO == user.NO);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						tree.Id = Convert.ToInt64(Regex.Replace(item.NO, @"^[A-Za-z]+", string.Empty));
						tree.PId = 0;
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						var filters = Builders<Models.User>.Filter.Where(p => p.Cantent == item.NO && p.UserType == Models.User.TypeClass.CONTENT);
						var count = tool.Count(filters);

						tree.IsParent = false;
						tree.icon = "/LinScript/zTree/css/img/diy/3.png";

						list.Add(tree);
					}
				}
			}
			else
			{
				var str = "";
				var idstr = id.ToString();
				if (idstr.Length == 6)
				{
					str = "SY" + idstr;
				}
				else if (idstr.Length == 5)
				{
					str = "CO" + idstr;

					var filter = Builders<Models.User>.Filter.Where(p => p.Cantent == str && p.UserType == Models.User.TypeClass.User);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						tree.Id = Convert.ToInt64(Regex.Replace(item.NO, @"^[A-Za-z]+", string.Empty));
						tree.PId = Convert.ToInt64(Regex.Replace(item.Cantent, @"^[A-Za-z]+", string.Empty));
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						tree.IsParent = false;
						tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						list.Add(tree);
					}

				}
				else if (idstr.Length == 4)
				{
					str = "CM" + idstr;
					var filter = Builders<Models.User>.Filter.Where(p => p.Cantent == str && p.UserType == Models.User.TypeClass.CONTENT);
					var users = tool.GetMany(filter);

					foreach (var item in users)
					{
						TreeModel tree = new TreeModel();
						tree.Id = Convert.ToInt64(Regex.Replace(item.NO, @"^[A-Za-z]+", string.Empty));
						tree.PId = Convert.ToInt64(Regex.Replace(item.Cantent, @"^[A-Za-z]+", string.Empty));
						tree.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
						tree.IsParent = false;
						var filters = Builders<Models.User>.Filter.Where(p => p.Cantent == item.NO && p.UserType == Models.User.TypeClass.User);
						var count = tool.Count(filters);
						if (count > 0)
						{
							tree.IsParent = true;
							tree.icon = "/LinScript/zTree/css/img/diy/1_open.png";
						}
						else
						{
							tree.IsParent = false;
							tree.icon = "/LinScript/zTree/css/img/diy/3.png";
						}
						list.Add(tree);
					}
				}

			}
			var jsonSerializerSettings = new JsonSerializerSettings
			{
				ContractResolver = new CamelCasePropertyNamesContractResolver()
			};
			return JsonConvert.SerializeObject(list, Formatting.None, jsonSerializerSettings);
		}

		/// <summary>
		/// 用户详情
		/// </summary>
		/// <param name="id">用户标识</param>
		/// <returns></returns>
		public JsonResult Detail(string id)
		{
			Repository.Repository tool = new Repository.Repository();

			if (id.Length == 6)
			{
				id = "SY" + id;
			}
			else if (id.Length == 5)
			{
				id = "CO" + id;
			}
			else if (id.Length == 4)
			{
				id = "CM" + id;
			}

			var filters = Builders<Models.User>.Filter.Where(p => p.NO == id);
			var member = tool.GetOne(filters);

			string arr = "";

			if (member.Bind != null && member.Bind.Count > 0)
			{
				foreach (var item in member.Bind)
				{
					arr += item + "|";
				}

				arr = arr.Substring(0, arr.Length - 1);

			}

			return Json(new { Code = "OK", Msg = "查询成功", MUP = string.IsNullOrEmpty(member.MUP) ? "无" : member.MUP, EUP = string.IsNullOrEmpty(member.EUP) ? "无" : member.EUP, Data = member, AddDT = member.AddDT.ToString("yyyy-MM-dd"), Level = Models.User.LevelClass.GetLevel(member.Level), Id = member._id.ToString(), Bind = arr });
		}

		/// <summary>
		/// 编辑上级
		/// </summary>
		/// <param name="id">用户id</param>
		/// <param name="no">上级编号</param>
		/// <param name="type">修改类型 1安置人 2推荐人</param>
		/// <returns></returns>
		public JsonResult EditUp(string id, string no, int type)
		{
			Repository.Repository tool = new Repository.Repository();

			var entity = tool.GetOne<Models.User>(id);
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			var filter = Builders<Models.User>.Filter.Where(p => p.NO == no && p.UserType == Models.User.TypeClass.User);

			var up = tool.GetOne<Models.User>(filter);
			if (up == null)
			{
				return Json(new { Code = "FAIL", Msg = "请检查上级编号是否正确" });
			}

			if (type == 1)
			{
				var update = Builders<Models.User>.Update.Set("EUP", no);
				var result = tool.UpdateOne(entity._id.ToString(), update);
			}
			else
			{
				var update = Builders<Models.User>.Update.Set("MUP", no);
				var result = tool.UpdateOne(entity._id.ToString(), update);
			}

			return Json(new { Code = "OK", Msg = "修改成功" });

		}

		public class TreeModel
		{
			public long Id { get; set; }

			public long PId { get; set; }

			public string icon { get; set; }

			public string Name { get; set; }
			public bool IsParent { get; set; }
		}

		/// <summary>
		/// 申请账户
		/// </summary>
		/// <param name="name">用户名</param>
		/// <param name="mUP">金钱上级</param>
		/// <param name="eUP">经验上级</param>
		/// <param name="content">服务中心或公司</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult SubmintMsg(string name, string mUP, string eUP, string content)
		{

			Repository.Repository tool = new Repository.Repository();
			var entity = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			Models.Message msg = new Models.Message();
			msg.AddDT = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
			msg.UserName = entity.Name;
			msg.Title = "账户申请";
			msg.MUP = string.IsNullOrEmpty(mUP) ? "无" : mUP;
			msg.EUP = string.IsNullOrEmpty(eUP) ? "无" : eUP;
			msg._id = ObjectId.GenerateNewId();
			msg.MId = msg._id.ToString();
			msg.UserNo = entity.NO;
			msg.Name = name;
			msg.Contre = string.IsNullOrEmpty(content) ? "无" : content;

			var result = tool.AddOne(msg);

			return Json(new { Code = "OK", Msg = "提交成功" });
		}

		/// <summary>
		/// 获取用户数据
		/// </summary>
		/// <param name="size"></param>
		/// <param name="index"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult GetMemberData(string key, int size = 10, int index = 1)
		{
			Repository.Repository tool = new Repository.Repository();

			if (string.IsNullOrEmpty(key))
			{
				var count = tool.Count<Models.User>(new BsonDocument());

				var list = tool.GetMany<Models.User>(new BsonDocument(), "AddDT:-1", size, index);

				ICollection<object> Entities = new List<object>() { };

				foreach (var item in list)
				{
					object i = new
					{
						Id = item._id.ToString(),
						NO = item.NO,
						MUP = string.IsNullOrEmpty(item.MUP) ? "无" : item.MUP,//推荐人
						EUP = string.IsNullOrEmpty(item.EUP) ? "无" : item.EUP,
						BankName = string.IsNullOrEmpty(item.BankName) ? "无" : item.BankName,
						Name = item.Name,
						UserName = item.UserName,
						Cantent = string.IsNullOrEmpty(item.Cantent) ? "无" : item.Cantent,
						Level = Models.User.LevelClass.GetLevel(item.Level),
						IsMStop = item.IsMStop ? "已关闭" : "正常",
						IsEStop = item.IsEStop ? "已关闭" : "正常",
						Money = item.Money.ToString("0.##"),
						BankNO = string.IsNullOrEmpty(item.BankNO) ? "无" : item.BankNO,
						Card = item.Card,
						AddDT = item.AddDT.ToString("yyyy-MM-dd"),
					};
					Entities.Add(i);
				}

				return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
			}
			else
			{

				var filter = Builders<Models.User>.Filter.Where(p => p.Name.Contains(key)|| p.NO.Contains(key)||p.UserName.Contains(key));

				var count = tool.Count<Models.User>(filter);

				var list = tool.GetMany<Models.User>(filter, "AddDT:-1", size, index);

				ICollection<object> Entities = new List<object>() { };

				foreach (var item in list)
				{
					object i = new
					{
						Id = item._id.ToString(),
						NO = item.NO,
						MUP = string.IsNullOrEmpty(item.MUP) ? "无" : item.MUP,//推荐人
						EUP = string.IsNullOrEmpty(item.EUP) ? "无" : item.EUP,
						BankName = string.IsNullOrEmpty(item.BankName) ? "无" : item.BankName,
						Name = item.Name,
						UserName = item.UserName,
						Cantent = string.IsNullOrEmpty(item.Cantent) ? "无" : item.Cantent,
						Level = Models.User.LevelClass.GetLevel(item.Level),
						IsMStop = item.IsMStop ? "已关闭" : "正常",
						IsEStop = item.IsEStop ? "已关闭" : "正常",
						Money = item.Money.ToString("0.##"),
						Card = item.Card,
						BankNO = string.IsNullOrEmpty(item.BankNO) ? "无" : item.BankNO,
						AddDT = item.AddDT.ToString("yyyy-MM-dd"),
					};
					Entities.Add(i);
				}

				return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
			}

		}



		/// <summary>
		/// 修改绑定服务中心
		/// </summary>
		/// <param name="userId">用户标识</param>
		/// <param name="arr">数组</param>
		/// <returns></returns>
		public JsonResult EditBind(string userId, List<string> arr)
		{
			Repository.Repository tool = new Repository.Repository();
			var entity = tool.GetOne<Models.User>(userId);
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}

			foreach (var item in arr)
			{
				var filter = Builders<Models.User>.Filter.Where(p => p.NO == item);
				var it = tool.GetOne<Models.User>(filter);


				if (it == null)
				{
					return Json(new { Code = "FAIL", Msg = "用户不存在" });
				}
				if (it.UserType != Models.User.TypeClass.COMPANY && it.UserType != Models.User.TypeClass.CONTENT)
				{
					return Json(new { Code = "FAIL", Msg = "该用户不是服务中心或公司" });
				}
			}

			var update = Builders<Models.User>.Update.Set("Bind", arr);

			var result = tool.UpdateOne(entity._id.ToString(), update);

			return Json(new { Code = "OK", Msg = "已修改" });

		}

	}
}